<template>
    <div>
      <h1>Real-Time Data from Server (SSE)</h1>
      <div v-if="messages.length === 0">Waiting for messages...</div>
      <div v-else>
        <ul>
          <li v-for="(message, index) in messages" :key="index">{{ message }}</li>
        </ul>
      </div>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        messages: [], // 存储从服务器接收到的消息
        eventSource: null, // 存储 SSE 连接对象
      };
    },
    created() {
      this.startSse();
    },
    beforeDestroy() {
      // 组件销毁时，关闭 SSE 连接
      if (this.eventSource) {
        this.eventSource.close();
      }
    },
    methods: {
      startSse() {
        // 创建 SSE 连接
        // this.eventSource = new EventSource("http://8.153.71.138:8411/sel/sse/sse");
        this.eventSource = new EventSource("http://192.168.110.48:9412/htp/sse/sse?userId=1&msg=%E8%A6%81%E4%B8%8E%E4%B8%80%E4%BD%8D%E7%BE%8E%E9%A3%9F%E7%B1%BB%E6%8A%96%E9%9F%B3%E8%BE%BE%E4%BA%BA%E5%BB%BA%E8%81%94%EF%BC%8C%E6%88%91%E6%89%93%E6%8B%9B%E5%91%BC%E7%AC%AC%E4%B8%80%E5%8F%A5%E5%9B%A0%E8%AF%A5%E8%AF%B4%E4%BB%80%E4%B9%88");
        // this.eventSource = new EventSource("https://ks-api.shangboyx.com/ks/sse/postSse?msg=%E8%A6%81%E4%B8%8E%E4%B8%80%E4%BD%8D%E7%BE%8E%E9%A3%9F%E7%B1%BB%E6%8A%96%E9%9F%B3%E8%BE%BE%E4%BA%BA%E5%BB%BA%E8%81%94%EF%BC%8C%E6%88%91%E6%89%93%E6%8B%9B%E5%91%BC%E7%AC%AC%E4%B8%80%E5%8F%A5%E5%9B%A0%E8%AF%A5%E8%AF%B4%E4%BB%80%E4%B9%88");
        

        // 监听服务器消息
        this.eventSource.onmessage = (event) => {
          console.log("Received message:", event.data);
          this.messages.push(event.data); // 将新消息添加到 messages 数组
        };
  
        // 错误处理
        this.eventSource.onerror = (error) => {
          console.error("SSE Error:", error);
          this.eventSource.close(); // 关闭连接
        };
      },
    },
  };
  </script>
  
